/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity.ConversationActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.adapter.NotifyMessageInteractionListener;
import com.srwl.mytx.adapter.SystemNotifyAdapter;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.ConversationService;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.im.conversation.SystemNotifyConversation;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.ArrayList;
import java.util.List;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;

/**
 * 系统通知页面
 */
public class SystemNotifyActivity extends BaseActivity implements NotifyMessageInteractionListener {
    private static final String TAG = "SystemNotifyActivity";
    public static final int REQUEST_CODE_TO_VERIFY_TOPIC = 5;
    private RecyclerView rv_notify;
    protected List<Message> notifyList = new ArrayList<>();
    protected RecyclerView.Adapter adapter;
    private MyTitleBar titleBar;
    private ProgressBar progressBar;
    private MaterialSmoothRefreshLayout refreshLayout;
    protected ConversationService conversationService;
    protected SystemNotifyConversation conversation;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_notice_message);
        titleBar = findViewById(R.id.title_bar);
        rv_notify = findViewById(R.id.rv_notify);
        progressBar = findViewById(R.id.progress_bar);
        refreshLayout = findViewById(R.id.refresh_layout);
        conversationService = IMSClientBootstrap.getInstance().getConversationService();
        initConversation();
        notifyList.addAll(conversation.firstLoadMessage(5));
        rv_notify.setLayoutManager(new LinearLayoutManager(this));
        rv_notify.setAdapter(adapter);
        initMessageListener();
        initRefreshLayout();
        ItemTouchHelper touchHelper = new ItemTouchHelper(new MyItemTouchHelperCallBack());
        touchHelper.attachToRecyclerView(rv_notify);
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出自定义对话

                ConfirmDialog dialog = new ConfirmDialog(SystemNotifyActivity.this, "提示", "确定删除所有通知消息吗？", true);
                dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        conversationService.deleteConversation(conversation);

                    }
                });
                dialog.show();
            }
        });
    }

    @NonNull
    protected void initConversation() {
        conversation = conversationService.getNotifyConversation(Constant.CONVERSATION_TYPE_SYSTEM);
        adapter = new SystemNotifyAdapter(this, notifyList, this);

    }

    private void initMessageListener() {
        conversation.setMessageListener(new Conversation.MessageListener() {
            @Override
            public void onPullDownLoadMoreLocalMessage(List<Message> messageList) {
//                refreshLayout.refreshComplete();
//                notifyList.addAll(0, messageList);
//                adapter.notifyItemRangeChanged(0, messageList.size());
//                adapter.notifyItemRangeChanged(messageList.size() + 1, notifyList.size() - (messageList.size() + 1));
//
                refreshLayout.refreshComplete();
                int startIndex = notifyList.size();
                notifyList.addAll(messageList);
                adapter.notifyItemRangeInserted(startIndex,messageList.size());
            }

            @Override
            public void onPullUpLoadMoreLocalMessage(List<Message> messages) {

            }

            @Override
            public void onNoMorePullDownMessage() {
                refreshLayout.refreshComplete();
            }

            @Override
            public void onReceiveMessage(Message message) {
                //因为通知类的消息可能是重复的，所以需要判断id 是否重复，重复的话，做更新处理。
                boolean isRepeat = false;
                for (int i = 0; i < notifyList.size(); i++) {
                    Message message1 = notifyList.get(i);
                    if (TextUtils.equals(message.getId(), message1.getId())) {
                        notifyList.set(i, message);
                        adapter.notifyItemChanged(i);
                        isRepeat = true;
                        break;
                    }
                }
                //非重复消息
                if (!isRepeat) { //通知类型的新消息，显示到第一个
                    notifyList.add(0, message);
                    adapter.notifyItemInserted(0);
                    rv_notify.smoothScrollToPosition(0);//移动消息到第一项
                }
            }

            @Override
            public void onMessageDelete(Message deleteMessage) {
                int index = notifyList.indexOf(deleteMessage);
                if (index != -1) {
                    notifyList.remove(index);
                    adapter.notifyItemRemoved(index);
                    adapter.notifyItemRangeChanged(index, notifyList.size() - index);
                }

            }

            @Override
            public void onDeleteAllMessage() {
                notifyList.clear();
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onMessageSendStateChange(Message message) {

            }

            @Override
            public void onMessageReadStateChange(Message message) {

            }

            @Override
            public void onTargetUserInfoRefresh(User targetUser) {

            }
        });

        conversation.setSystemNotifyListener(new SystemNotifyConversation.SystemNotifyListener() {
            @Override
            public void onMessageChange(Message notify) {
                for (int i = 0; i < notifyList.size(); i++) {
                    Message message1 = notifyList.get(i);
                    if (TextUtils.equals(notify.getId(), message1.getId())) {
                        notifyList.set(i, notify);
                        adapter.notifyItemChanged(i);
                        break;
                    }
                }
            }
        });
    }

    void initRefreshLayout() {
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);

        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                // conversation.pullDownLoadMoreMessage();


            }

            @Override
            public void onLoadingMore() {
                //通知类型的消息，是新消息显示到最顶部，上拉加载的消息，显示到底部，
                //这儿虽然是上拉，调用的却是 会话中的下拉加载更多消息的方法，因为最初，是基于一对一im聊天设计，在im聊天里面，下拉才是加载更多的消息。
                conversation.pullDownLoadMoreMessage();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        conversation.clear();
    }


    @Override
    protected void onResume() {
        super.onResume();
        conversation.setActivityInBackstage(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        conversation.setActivityInBackstage(true);
    }

    @Override
    public void onItemLongClick(Message message) {
        ConfirmDialog dialog = new ConfirmDialog(this, "提示", "确定删除该消息吗？", true);
        dialog.setConfirmListener(() -> conversation.deleteMessage(message));
        dialog.show();
    }

    @Override
    public void onMessageRead(int position) {

    }

    public class MyItemTouchHelperCallBack extends ItemTouchHelper.Callback {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFlags = ItemTouchHelper.ACTION_STATE_IDLE;
            int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            int position = viewHolder.getAdapterPosition();
            conversation.deleteMessage(notifyList.get(position));
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        //主题状态改变后，更新进通知列表中
        if (requestCode == REQUEST_CODE_TO_VERIFY_TOPIC) {
            Topic updateTopic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
            if (updateTopic == null) {
                return;
            }
            for (int i = 0; i < notifyList.size(); i++) {
                Message notify = notifyList.get(i);
                if (notify.getSubType() == Constant.PUSH_MESSAGE_TOPIC_VERIFY) {
                    Topic topic = JSONObject.parseObject(notify.getExtraData(), Topic.class);
                    if (topic == null) {
                        continue;
                    }
                    if (TextUtils.equals(updateTopic.getId(), topic.getId())) {
                        notify.setExtraData(JSONObject.toJSONString(updateTopic));
                        adapter.notifyItemChanged(i);
                        DBManager.getInstance().getDaoSession().getMessageDao().update(notify);
                        break;
                    }
                }
            }

        }
    }
}
